<template>
  <div class="profile-container">
    <div class="header">
      <button class="back-button" @click="handleBack">
        <img src="../assets/返回.svg" alt="返回" class="back-image" style="width: 40px; height: 40px;" />
      </button>
      <h1 class="title">个人资料</h1>
    </div>

    <div class="content-card">
      <!-- 头像部分 -->
      <div class="avatar-section">
        <div class="avatar-preview" @click="triggerFileInput">
          <img v-if="avatarPreview" :src="avatarPreview" alt="用户头像" class="avatar-image" />
          <i v-else class="fas fa-user-circle default-avatar"></i>
        </div>
        <p class="avatar-hint">点击选择头像</p>
        <input type="file" ref="fileInput" accept="image/*" @change="handleAvatarSelect" class="file-input" />
        <button class="save-avatar-button" :disabled="!selectedFile" @click="uploadAvatar">
          确定修改头像
        </button>
      </div>

      <!-- 手机号 -->
      <div class="phone-section">
        <label for="phone" class="input-label">手机号</label>
        <input id="phone" v-model="phone" type="text" disabled class="nickname-input bg-gray-100 cursor-not-allowed" />
      </div>

      <!-- 昵称 -->
      <div class="nickname-section">
        <label for="nickname" class="input-label">昵称</label>
        <div class="input-wrapper">
          <input id="nickname" v-model="nickname" type="text" maxlength="12" placeholder="请输入昵称" class="nickname-input"
            @input="updateCharCount" />
          <span class="char-count" :class="{ 'error': isOverLimit }">
            {{ charCount }}/12
          </span>
        </div>
        <button class="save-button" :disabled="isOverLimit || !nickname" @click="saveNickname">
          保存昵称
        </button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
const router = useRouter();
const fileInput = ref<HTMLInputElement | null>(null);
const avatarPreview = ref<string>(''); // 显示预览图
const selectedFile = ref<File | null>(null); // 存储选择的头像文件
const phone = ref<string>(localStorage.getItem('loggedInPhone') || '');
const nickname = ref<string>('请修改名称');
const charCount = ref<number>(nickname.value.length);
const isOverLimit = ref<boolean>(false);

// 打开文件选择框
const triggerFileInput = () => {
  fileInput.value?.click();
};

// 头像预览和上传分离
const handleAvatarSelect = (e: Event) => {
  const target = e.target as HTMLInputElement;
  const file = target.files?.[0];

  if (!file) return;

  if (file.size > 10 * 1024 * 1024) {
    alert('图片大小不能超过10MB');
    return;
  }

  selectedFile.value = file;

  // 本地预览（不是最终图片地址）
  const reader = new FileReader();
  reader.onload = (event) => {
    avatarPreview.value = event.target?.result as string;
  };
  reader.readAsDataURL(file);
};

// 上传头像并替换预览图为服务器返回地址
const uploadAvatar = async () => {
  if (!selectedFile.value || !phone.value) {
    alert('请先选择图片');
    return;
  }

  try {
    const formData = new FormData();
    formData.append('file', selectedFile.value);
    formData.append('phone', phone.value);

    const response = await axios.post('http://localhost:8080/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    if (response.data.code === 200) {
      // ✅ 成功后使用服务器返回的图片地址作为头像预览
      avatarPreview.value = response.data.data;
      selectedFile.value = null;
      alert('头像修改成功');
    } else {
      alert('头像修改失败：' + response.data.msg);
    }
  } catch (error) {
    console.error('上传头像出错：', error);
    alert('头像上传失败，请检查网络');
  }
};

onMounted(async () => {
  updateCharCount();
  if (phone.value) {
    try {
      const res = await axios.get(`http://localhost:8080/api/user-pic?phone=${phone.value}`);
      if (res.data.code === 200 && res.data.data) {
        avatarPreview.value = res.data.data; // 加载服务器头像地址
      }
    } catch (error) {
      console.warn('获取头像失败', error);
    }
  }
});

// 更新字符计数器
const updateCharCount = () => {
  charCount.value = nickname.value.length;
  isOverLimit.value = charCount.value > 12;
};

// 保存昵称
const saveNickname = async () => {
  if (!phone.value) {
    alert('手机号不存在');
    return;
  }

  try {
    const response = await axios.post('http://localhost:8080/api/auth/update-username', {
      phone: phone.value,
      newUsername: nickname.value
    });

    if (response.data.code === 200) {
      alert('昵称修改成功');
      router.push({ name: 'Myself' });
    } else {
      alert('修改失败：' + response.data.msg);
    }
  } catch (error) {
    console.error('修改昵称失败', error);
    alert('修改失败，请检查网络');
  }
};

const handleBack = () => {
  router.push({ name: 'Myself' });
};

onMounted(() => {
  updateCharCount();
});
</script>

<style scoped>
@import '../assets/css/personalData.css';

.save-avatar-button {
  margin-top: 8px;
  background-color: #4caf50;
  color: white;
  border: none;
  padding: 8px 14px;
  border-radius: 6px;
  cursor: pointer;
}

.phone-section {
  margin-top: 20px;
}

.input-label {
  font-weight: bold;
  display: block;
  margin-bottom: 6px;
}
</style>
